package com.authine.cloudpivot.ext.dto.model.invoice;

import com.authine.cloudpivot.ext.utils.RegexUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.Serializable;
import java.util.Optional;

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
@Slf4j
public class InvoiceDetailExtendsAttr implements Serializable {

    private static final long serialVersionUID = -1503811123871750536L;
    /**
     * 订单商品号
     */
    private String orderGoodsId;
    /**
     * 供应商订单号
     */
    private String vendorOrderId;
    /**
     * 客户订单号
     */
    private String customerOrderId;

    private String taxRate;
    /**
     * 审批理由
     */
    private String reason;
    /**
     * 是否需要审批
     */
    private Boolean ifApprove;

    public static Optional<InvoiceDetailExtendsAttr> conversion(String value) {

        ObjectMapper objectMapper = new ObjectMapper();
        try {
            if (!RegexUtils.notNull(value)) {
                return Optional.empty();
            }
            return Optional.ofNullable(objectMapper.readValue(value, InvoiceDetailExtendsAttr.class));
        } catch (IOException ex) {

            log.error("发票明细拓展属性转换错误", ex);
            return Optional.empty();
        }
    }

    public static Optional<String> conversion(InvoiceDetailExtendsAttr value) {

        ObjectMapper objectMapper = new ObjectMapper();
        try {

            return Optional.ofNullable(objectMapper.writeValueAsString(value));
        } catch (IOException ex) {

            log.error("发票明细拓展属性转换错误",ex);
            return Optional.empty();
        }
    }

    public static String offset(String targetValue) {

        ObjectMapper objectMapper = new ObjectMapper();
        try {
            InvoiceDetailExtendsAttr e = objectMapper.readValue(targetValue, InvoiceDetailExtendsAttr.class);
            return objectMapper.writeValueAsString(InvoiceDetailExtendsAttr.builder().customerOrderId(e.customerOrderId).vendorOrderId(e.vendorOrderId).orderGoodsId(e.orderGoodsId).build());
        } catch (IOException ex) {
            log.error("发票明细拓展属性转换错误", ex);
            return "";
        }
    }

    public static String getDefault() {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            return objectMapper.writeValueAsString(InvoiceDetailExtendsAttr.builder().ifApprove(false).build());
        } catch (JsonProcessingException e) {
            log.error("发票明细拓展属性转换错误", e);
            return "";
        }
    }

    public Boolean getIfApprove() {
        return null == ifApprove ? false : ifApprove;
    }
}
